package com.xd.clap.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xd.clap.entity.*;
import com.xd.clap.entity.request.OrderParam;
import com.xd.clap.entity.request.PageParam;
import com.xd.clap.entity.request.ProductParam;
import com.xd.clap.entity.response.OrderDetail;
import com.xd.clap.entity.response.Result;
import com.xd.clap.mapper.OrderInfoMapper;
import com.xd.clap.mapper.OrderMapper;
import com.xd.clap.mapper.ProductMapper;
import com.xd.clap.mapper.UserMapper;
import com.xd.clap.services.OrderService;
import com.xd.clap.services.RateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper om;

    @Resource
    private UserMapper um;

    @Resource
    private OrderInfoMapper oim;

    @Resource
    private ProductMapper pm;

    @Resource
    private RateService rs;

    @Override
    public Result createOrder(OrderParam orderParam) {
        String phone = orderParam.getPhone();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = um.selectOne(queryWrapper);
        if (user.getPoints() < orderParam.getTotal()) {
            return Result.success(null, "积分不足");
        }
        QueryWrapper<User> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("phone", phone);
        user.setPoints(user.getPoints() - orderParam.getTotal());
        int updated = um.update(user, updateWrapper);

        if (updated > 0) {
            //订单商品列表
            List<ProductParam> productParamList = orderParam.getProductParamList();
            //创建订单
            Orders order = new Orders();
            order.setPhone(phone);
            order.setCreateTime(new Date());
            order.setTotal(orderParam.getTotal());
            //时间（精确到秒）
            DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String localDate = LocalDateTime.now().format(ofPattern);
            //生成订单号
            order.setOrderId(localDate);
            order.setState(1);
            try {
                om.insert(order);
            } catch (Exception e) {
                return Result.success(null, "下单失败");
            }
            //生成订单详情
            for (ProductParam productParam : productParamList) {
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setPid(productParam.getId());
                orderInfo.setNumber(productParam.getNumber());
                orderInfo.setOrderId(localDate);
                oim.insert(orderInfo);
            }
            Rate rate = new Rate();
            rate.setPhone(phone);
            rate.setContent("积分换购");
            rate.setCreateTime(new Date());
            rate.setRate(-orderParam.getTotal());
            if (rs.uploadRate(rate))
                return Result.success(user, "下单成功");
            else
                return Result.fail(0, "下单失败");
        }
        return Result.fail(0, "下单失败");
    }

    @Override
    public Result getOrdersPage(PageParam pageParam) {
        Page<Orders> ordersPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        Page<OrderDetail> orderDetailPage = new Page<>();
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(pageParam.getMessage())) {
            pageParam.setMessage("");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("phone", pageParam.getMessage());
        List<User> userList = um.selectList(userQueryWrapper);
        if (userList.isEmpty()) {
            return Result.success(ordersPage, "加载成功");
        }
        for (User user : userList) {
            if (pageParam.getStateCode() != null && pageParam.getStateCode() > 0) {
                if (pageParam.getStateCode() < 3) {
                    queryWrapper.eq("state", pageParam.getStateCode());
                } else {
                    queryWrapper.ge("state", 3);
                }
            }
            queryWrapper.eq("phone", user.getPhone()).or();
        }
        queryWrapper.orderByDesc("create_time");
        IPage<Orders> ordersIPage = om.selectPage(ordersPage, queryWrapper);
        return getResult(ordersIPage, orderDetailPage);
    }


    @Override
    public Result getOrders(PageParam pageParam) {
        Page<Orders> ordersPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", pageParam.getPhone());
        if (pageParam.getStateCode() != null && pageParam.getStateCode() > 0) {
            if (pageParam.getStateCode() < 3) {
                queryWrapper.eq("state", pageParam.getStateCode());
            } else {
                queryWrapper.ge("state", 3);
            }
        }
        queryWrapper.le("state", 4);
        queryWrapper.orderByDesc("create_time");
        IPage<Orders> ordersIPage = om.selectPage(ordersPage, queryWrapper);
        Page<OrderDetail> orderDetailPage = new Page<>();
        return getResult(ordersIPage, orderDetailPage);
    }

    private Result getResult(IPage<Orders> ordersPage, Page<OrderDetail> orderDetailPage) {
        BeanUtils.copyProperties(ordersPage, orderDetailPage, "records");
        List<Orders> records = ordersPage.getRecords();
        List<OrderDetail> orderDetailList = records.stream().map(this::getOrderDetail).collect(Collectors.toList());
        orderDetailPage.setRecords(orderDetailList);
        return Result.success(orderDetailPage, "加载成功");
    }

    @Override
    public Result updateState(Orders orders) {
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", orders.getOrderId());
        updateWrapper.set("state", orders.getState());
        if (orders.getState() == 1) {
            //重新下单
            Integer total = orders.getTotal();
            String phone = orders.getPhone();
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = um.selectOne(queryWrapper);
            if (user.getPoints() < total) {
                return Result.fail(0, "积分不足");
            }
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            user.setPoints(user.getPoints() - total);
            int updated = um.update(user, wrapper);
            Rate rate = new Rate();
            rate.setPhone(phone);
            rate.setContent("积分换购");
            rate.setCreateTime(new Date());
            rate.setRate(-total);
            if (updated == 0 || !rs.uploadRate(rate)) {
                return Result.fail(0, "下单失败");
            }
        } else if (orders.getState() == 4) {
            //取消下单
            int total = (int) (orders.getTotal() * 0.9);
            String phone = orders.getPhone();
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.eq("phone", phone);
            wrapper.setSql("`points`=`points`+" + total);
            int updated = um.update(null, wrapper);
            Rate rate = new Rate();
            rate.setPhone(phone);
            rate.setContent("订单取消");
            rate.setCreateTime(new Date());
            rate.setRate(total);
            if (updated == 0 || !rs.uploadRate(rate)) {
                return Result.fail(0, "取消失败");
            }
        }
        int update = om.update(null, updateWrapper);
        if (update < 1) {
            return Result.fail(0, "更新失败！");
        }
        return Result.success(update, "更新成功！");
    }

    //返回订单详细信息
    public OrderDetail getOrderDetail(Orders orders) {
        QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
        orderInfoQueryWrapper.eq("order_id", orders.getOrderId());
        List<OrderInfo> orderInfoList = oim.selectList(orderInfoQueryWrapper);
        //根据订单明细获取商品列表
        List<ProductParam> productParamList = orderInfoList.stream().map((item) -> {
            ProductParam productParam = new ProductParam();
            Product product = pm.selectById(item.getPid());
            // 修复商品被删除后无法查询订单明细的异常问题
            if (product == null) return null;
            productParam.setId(product.getId());
            productParam.setName(product.getName());
            productParam.setPrice(product.getPrice());
            productParam.setNumber(item.getNumber());
            return productParam;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        OrderDetail orderDetail = new OrderDetail();
        //订单id
        orderDetail.setId(orders.getId());
        //订单号
        orderDetail.setOrderId(orders.getOrderId());
       //用户手机
        orderDetail.setPhone(orders.getPhone());
        //下单时间
        orderDetail.setCreateTime(orders.getCreateTime());
        //订单状态
        orderDetail.setState(orders.getState());
        //总价
        orderDetail.setTotal(orders.getTotal());
        //商品列表
        orderDetail.setProductList(productParamList);
        return orderDetail;
    }

}
